package com.hxci.pointmap.controller;

import com.hxci.pointmap.model.EnvironmentData;
import com.hxci.pointmap.service.DataGeneratorService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Locale;

@WebServlet("/data")
public class DataController extends HttpServlet {
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        String actionType = req.getParameter("actionType");
        PrintWriter out = resp.getWriter();

        if ("getEnvironmentData".equals(actionType)) {
            // 获取请求参数，默认生成24小时数据
            String dataType = req.getParameter("dataType");
            List<EnvironmentData> dataList;
            

            DataGeneratorService dataGeneratorService = new DataGeneratorService();

            if ("7days".equals(dataType)) {
                dataList = dataGeneratorService.generateLast7DaysData();
            } else {
                // 默认返回24小时数据
                dataList = dataGeneratorService.generateLast24HoursData();
            }

            // 转换为JSON格式返回
            String json = convertToJson(dataList);
            out.print(json);
        } else if ("getRandomData".equals(actionType)) {
            // 生成指定数量的随机数据
            int count = 10; // 默认生成10条数据
            String countStr = req.getParameter("count");
            if (countStr != null && !countStr.isEmpty()) {
                try {
                    count = Integer.parseInt(countStr);
                } catch (NumberFormatException e) {
                    // 使用默认值
                }
            }

            // 每次请求创建新的DataGeneratorService实例，确保生成新的随机数据
            DataGeneratorService dataGeneratorService = new DataGeneratorService();
            List<EnvironmentData> dataList = dataGeneratorService.generateEnvironmentData(count);
            String json = convertToJson(dataList);
            out.print(json);
        } else {
            // 不支持的请求类型
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.print("{\"error\":\"Unsupported action type\"}");
        }
    }

    // 将EnvironmentData列表转换为JSON字符串
    private String convertToJson(List<EnvironmentData> dataList) {
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("[");
        
        for (int i = 0; i < dataList.size(); i++) {
            EnvironmentData data = dataList.get(i);
            jsonBuilder.append("{");
            jsonBuilder.append("\"id\":").append(data.getId()).append(",");
            jsonBuilder.append("\"deviceName\":\"").append(data.getDeviceName()).append("\",");
            jsonBuilder.append("\"temperature\":").append(data.getTemperature()).append(",");
            jsonBuilder.append("\"humidity\":").append(data.getHumidity()).append(",");
            jsonBuilder.append("\"light\":").append(data.getLight()).append(",");
            jsonBuilder.append("\"co2\":").append(data.getCo2()).append(",");
            jsonBuilder.append("\"recordTime\":\"").append(dateFormat.format(data.getRecordTime())).append("\"");
            jsonBuilder.append("}");
            
            if (i < dataList.size() - 1) {
                jsonBuilder.append(",");
            }
        }
        
        jsonBuilder.append("]");
        return jsonBuilder.toString();
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
